import { Button, Image, View } from '@tarojs/components';
import { useState } from 'react';
import { AtButton, AtInput } from 'taro-ui';
import Taro from '@tarojs/taro';
import { request, uploadAvatar } from 'src/request';
import avatarDefault from 'src/assets/icon/avatar-default.png'
import { useProfile } from 'src/state/profile';

import './index.less';

type CreateUserData = {
  name?: string
  avatar?: string
}

function Register() {
  const [data, setData] = useState<CreateUserData>({})
  const { fetchProfile } = useProfile()

  const postData = (_data: CreateUserData) => {
    return request.post('/user', _data)
  }

  const handleChange = (type: keyof CreateUserData) => {
    return (value) => {
      setData({
        ...data,
        [type]: value
      })
    }
  }

  const handleChooseAvatar = async (e) => {
    // 图片临时路径
    const { avatarUrl } = e.detail
    try {
      Taro.showLoading({
        title: '上传中',
      })
      const fileId = await uploadAvatar(avatarUrl)
      handleChange('avatar')(fileId)
    } finally {
      Taro.hideLoading()
    }
  }

  const handleConfirm = () => {
    if (!data.name || !data.avatar) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
      })
      return
    }
    postData(data).then(() => {
      Taro.showToast({
        title: '注册成功',
        icon: 'none',
      })
      setTimeout(() => {
        fetchProfile()
        Taro.redirectTo({
          url: '/pages/apply/index'
        })
      }, 1000)
    })
  }

  return (
    <View>
      <View className='header'>
        <View className='header-name'>
          注册
        </View>
      </View>
      <View className='body'>
        <View className='choose-avatar-wrap'>
          <Button openType='chooseAvatar' className='choose-avatar' onChooseAvatar={handleChooseAvatar}>
            <Image src={data.avatar || avatarDefault} />
          </Button>
        </View>
        <AtInput
          // @ts-ignore
          type='nickname'
          placeholder='请输入昵称'
          value={data.name}
          onChange={handleChange('name')}
        />
        <AtButton type='primary' onClick={handleConfirm}>
          注册
        </AtButton>
      </View>
    </View>
  );
}

export default Register;
